<template>
  <div class="app-container">
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :height="tableHeight"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :default-sort="{prop: 'sort', order: 'ascending'}"
    >
      <el-table-column fixed="left" label="序号" prop="sort" sortable align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模块名称" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.moduleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模块编码" width="110px" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.moduleCode }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="访问地址" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type===1?'目录':'页面' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.isEffective | statusFilter">
            <i v-if="row.isEffective" class="el-icon-check" />
            <i v-else class="el-icon-close" style="right:0" />
            {{ row.isEffective?'有效':'无效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleModifyStatus(row,'deleted')">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" /> -->

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :inline="true" class="demo-form-inline" :rules="rules" :model="temp" label-position="right" label-width="120px">
        <el-form-item label="模块名称" prop="moduleName">
          <el-input v-model="temp.moduleName" />
        </el-form-item>
        <el-form-item label="模块编码" prop="moduleCode">
          <el-input v-model="temp.moduleCode" />
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input v-model="temp.sort" />
        </el-form-item>
        <el-form-item label="模块分类">
          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否有效" style="display:block;">
          <el-checkbox v-model="temp.isEffective"> 注意：禁用该模块后，将不会显示。</el-checkbox>
        </el-form-item>
        <el-form-item label="访问地址" class="input-width-full">
          <el-input v-model="temp.url" />
        </el-form-item>
        <el-form-item label="备注说明" class="input-width-full">
          <el-input v-model="temp.memo" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { GetModuleChild, EditModule, AddModule, DeleteModule } from '@/api/system'
import waves from '@/directive/waves' // Waves directive
import * as R from 'ramda'

export default {
  name: 'ComplexTable',
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = status ? 'success' : 'danger'
      return statusMap
    }
  },
  props: {
    tableHeight: {
      type: Number,
      default: 500
    },
    tableNode: {
      type: Object,
      default: (val) => {
        return {
          selected: true,
          title: ''
        }
      }
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['模块', '页面'],
      showReviewer: false,
      temp: {
        grade: 0,
        id: 0,
        isEffective: true,
        isRemove: false,
        memo: null,
        moduleCode: '',
        moduleName: '',
        sort: 0,
        superiorModule: 0,
        type: 0,
        url: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        moduleName: [{ required: true, message: '模块名称不能为空', trigger: 'change' }],
        moduleCode: [{ required: true, message: '模块编码不能为空', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      parentId: 1,
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList(parentId = 1) {
      this.listLoading = true
      GetModuleChild(parentId).then(response => {
        this.list = response.data
        this.total = response.data.length
        this.listLoading = false
        this.parentId = parentId
      })
    },
    handleModifyStatus(row, status) {
      DeleteModule(row.id).then(response => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
        var isEven = n => n.id !== row.id
        this.list = R.filter(isEven)(this.list)
        this.$emit('getTreeData')
      })
    },
    resetTemp(id) {
      this.temp = {
        grade: 0,
        id,
        isEffective: true,
        isRemove: false,
        memo: '',
        moduleCode: '',
        moduleName: '',
        sort: 0,
        superiorModule: 0,
        type: '页面',
        url: ''
      }
    },
    handleCreate(id) {
      this.resetTemp(id)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempParma = this.temp
          tempParma.superiorModule = this.temp.id
          tempParma.id = 0
          tempParma.type = this.temp.type === '模块' ? 1 : 2
          AddModule(tempParma).then(() => {
            this.getList(this.parentId)
            this.dialogFormVisible = false
            this.$emit('getTreeData')
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.type = this.temp.type === 1 ? '目录' : '页面'
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.type = tempData.type === '模块' ? 1 : 2
          // EditModule
          EditModule(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$emit('getTreeData')
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    }
  }
}
</script>

<style>
.app-container {
  height: 100%;
}
.input-width-full {
  display: block;
  width: 100%;
}
.input-width-full .el-form-item__content {
  width: 75%;
}
</style>
